package com.softeem.oss_music.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.oss_music.comm.R;
import com.softeem.oss_music.entity.Music;
import com.softeem.oss_music.entity.MusicListDetails;
import com.softeem.oss_music.service.MusicListDetailsService;
import com.softeem.oss_music.service.MusicService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;
import java.util.List;
@Tag(name = "音乐管理")
@RestController
public class MusicController {
    @Autowired
    private MusicService musicService;
    @Autowired
    private  MusicListDetailsService musicListDetailsService;
    @Operation(summary = "音乐列表", description = "根据提供的页码和数据链条实现分页查询")
    @Parameters({
            @Parameter(name = "page", description = "页码"),
            @Parameter(name = "limit", description = "数据条数")
    })
    @GetMapping("/music/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer limit){
        IPage<Music> iPage = new Page<Music>(page,limit);
        List<Music> list = musicService.list(iPage);
        //查询总记录数
        long count = musicService.count();
        return R.success().setData(list).setCount( count);
    }

    @Operation (summary = "音乐详情", description = "根据id查询音乐详情")
    @Parameters({
            @Parameter(name = "id", description = "音乐id")
    })
    @GetMapping("/music/details")
    public R details(Integer id){
        return musicService.musicDetails(id);
    }
    @Operation (summary = "添加音乐", description = "添加音乐")
    @PostMapping("/music/add")
    public  R addMusic(@RequestBody Music music){
        boolean b = musicService.save(music);
        return b ? R.success().setMessage("添加成功") : R.error().setMessage("添加失败");
    }
    @Operation (summary = "删除音乐", description = "根据id删除音乐")
    @Parameters({
            @Parameter(name = "id", description = "音乐id")
    })
    @DeleteMapping("/music/del")
    public R delete(Integer id){
        //根据id查询是否有关联的歌单
        QueryWrapper<MusicListDetails> query = Wrappers.query(MusicListDetails.class);
        query.eq("music_id",id);
        List<MusicListDetails> list = musicListDetailsService.list(query);
        if (list.size()>0){
            return R.error().setMessage("删除失败，请先删除歌单中的歌曲");
        }
        return musicService.removeById(id) ? R.success().setMessage("删除成功") : R.error().setMessage("删除失败");
    }
}
